const path = require("path");
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const { DefinePlugin } = require('webpack')

class MyPlugin {
  // apply方法是webpack在初始化时，注册plugin调用的方法
  apply (compiler) {
    console.log('start MyPlugin')
    // tap相当于订阅webpack的钩子事件。
    compiler.hooks.emit.tap('MyPligin', compilation => {
      // compilation 可以理解为此次打包的上下文
      for (const name in compilation.assets) {
        // console.log('~', name)
        if (name.endsWith('.js')) {
          const contents = compilation.assets[name].source()
          const withOutComments = contents.replace(/\/*\*+\*\//g, '')
          compilation.assets[name] = {
            source: () => withOutComments,
            size: () => withOutComments.length
          }
        }
      }
    })
  }
}

module.exports = {
  mode: "none",
  entry: "./src/main.js",
  output: {
    filename: "bundle.js",
    path: path.resolve(__dirname, "dist"),
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: "babel-loader",
      },
      {
        test: /\.css$/,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /\.png$/,
        use: {
          loader: "url-loader",
          options: {
            limit: 10 * 1024,
          },
        },
      },
    ],
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HTMLWebpackPlugin({
      title: 'HTML plugin',
      template: './template.html'
    }),
    new MyPlugin(),
    new DefinePlugin({
      API_BASE_URL: '"https://api.example.com"'
    })
  ],
  optimization: {
    usedExports: true, // 只导出外部使用的成员
    minimize: true, // 压缩代码
  }
};
